package com.tao.util.pack;

import java.util.List;

import com.google.gson.Gson;
import com.tao.util.ThreadLostener;
import com.tao.util.Utils;
import com.tao.util.pack.HeartBeatThread.OnExitMsgListener;
import com.tao.util.pack.HeartBeatThread.OnNewMsgListener;
import com.tao.util.pack.HeartBeatThread.OnStatsMsgListener;
import com.tao.util.pack.WaitScanAndLoginThread.OnScanListener;



public class WeChatClass {
	boolean isBeat=false;
	//************** 一些变量
	public String uuid;
	public String baseUrl;
	public String skey;
	public String wxsid;
	public String pass_ticket;
	public String wxuin;
	public String keyString;
	public String cookie;
	public BaseResponeBean initbean;
	public String time;
	
	public String initResult ;
	//***************监听接口
	
	Gson gson=new Gson();
	private HttpClient hc=HttpClient.getInstance();
	private StringSubClass ss=new StringSubClass();
	private OnScanListener mScanListener;
	private OnNewMsgListener mNewMsgListener;
	private OnExitMsgListener mExitMsgListener;
	private OnLoadQrCodeListener mQrCodeListener;
	private OnStatsMsgListener mStatsMsgListener;
	private OnInitMsgListener mInitMsgListener;
	private OnContentListener mContentListener;
	
	
	//获取图片的byte数组，主要用于安卓端bitmap展示。pc可不用
	interface OnLoadQrCodeListener {
		void onLoadSuccess(byte[] imageBytes);
	}
	public interface OnInitMsgListener{//用户监听器
		void onInitMsg(String text,String[] login );
		
	}
	public interface OnContentListener{//用户监听器
		void onContentMsg(String text,String uin);
		
	}
	
	
	/**
	 * 必须先设置两个监听器，然后调用这个方法
	 */
	public String gogogo(){
		
		String result= "";
		System.setProperty ("jsse.enableSNIExtension", "false");//避免ssl异常
		
		 result=hc.post("https://login.weixin.qq.com/jslogin","",
				"appid=wx782c26e4c19acffb&fun=new&lang=zh_CN&_="+System.currentTimeMillis());
		
		 for(int i = 0;i<3;i++){
			 result=hc.post("https://login.weixin.qq.com/jslogin","",
						"appid=wx782c26e4c19acffb&fun=new&lang=zh_CN&_="+System.currentTimeMillis());
		
			 if(result==null||result.equals("")){
			 continue;
			 }
		 }
		uuid=ss.subStringOne(result, ".uuid = \"", "\";");//得到uuid
		//开启下载二维码的线程,安卓端需要把这里设置为false
		/*DownLoadQrCodeThread qrCodeThread=new DownLoadQrCodeThread("https://login.weixin.qq.com/qrcode/"+uuid+"?t=webwx&_=", true);
		qrCodeThread.setListener(new OnloadQrCodeFinnishListener() {
			
			@Override
			public void onLoadSuccess(byte[] imageBytes) {
				if (mQrCodeListener!=null) {
					mQrCodeListener.onLoadSuccess(imageBytes);
				}
				
				
			}
		});*/
		//qrCodeThread.start();
		
		//二维码下载完成，开启轮询线程等待扫描二维码和登陆
		WaitScanAndLoginThread loginThread=new WaitScanAndLoginThread(uuid,WeChatClass.this);
		loginThread.setmScanListener(mScanListener);
		loginThread.start();
		
		
		return uuid;
		
	}//uuid
	
	
	
	/**
	 * 在成功登陆后初始化微信相关参数
	 */
	 void init(){
			 InitThread initThread = new InitThread();
			 initThread.start();
	}
	
	
	
	/**
	 * 初始化后可选择性获取好友和群
	 */
	public void getFriendAndGroup(String initResult){
		
		System.out.println("获取群号");
		String groupResult=hc.post(baseUrl+"/webwxgetcontact?r="+System.currentTimeMillis()+"&pass_ticket="+pass_ticket+"&skey="+skey,cookie,"{}");
		
		BaseResponeBean brespon = new Gson().fromJson(initResult, BaseResponeBean.class);
		
		mContentListener.onContentMsg(groupResult,brespon.getUser().getUin());
		
//		System.out.println(groupResult);
		//System.err.println(new Gson().fromJson(groupResult, BaseResponeBean.class).getMemberList());
	}
	/**
	 * 同步syncKeys，每次获取到新消息后都要同步
	 */
	public void syncKeys(String reslut) {
		initbean=gson.fromJson(reslut, BaseResponeBean.class);
		keyString="";
		List<BaseResponeBean.SyncKeyEntity.ListEntity> keyList = initbean.getSyncKey().getList();
		for (BaseResponeBean.SyncKeyEntity.ListEntity listEntity : keyList) {
			keyString+=listEntity.getKey()+"_"+listEntity.getVal()+"|";
		}
		keyString=keyString.substring(0, keyString.length()-1);
	}
	
	//设置各种监听器
	public void setmScanListener(OnScanListener mScanListener) {
		this.mScanListener = mScanListener;
	}
	public void setmNewMsgListener(OnNewMsgListener mNewMsgListener) {
		this.mNewMsgListener = mNewMsgListener;
	}
	public void setmQrCodeListener(OnLoadQrCodeListener mQrCodeListener) {
		this.mQrCodeListener = mQrCodeListener;
	}
	public void setmExitMsgListener(OnExitMsgListener mExitMsgListener) {
		this.mExitMsgListener = mExitMsgListener;
	}
	public void setmInitMsgListener(OnInitMsgListener mInitMsgListener) {
		this.mInitMsgListener = mInitMsgListener;
	}
	public void setmContentListener(OnContentListener mContentListener) {
		this.mContentListener = mContentListener;
	}
	public void setmStatsMsgListener(
			 OnStatsMsgListener mStatsMsgListener) {
		this.mStatsMsgListener = mStatsMsgListener;
	}


	class InitThread extends Thread{
		   
			@Override
			public void run() {
				String data="{\"BaseRequest\":{\"Uin\":\""+wxuin+"\",\"Sid\":\""+wxsid+"\",\"Skey\":\""+skey+"\",\"DeviceID\":\""+Utils.getDeviceID()+"\"}}";
				hc.contentType="application/json";
				System.out.println("获取微信号");
				 initResult = hc.post(baseUrl+"/webwxinit?r="+System.currentTimeMillis(),cookie,
						data);
				
				System.out.println("是否已开启心跳线程");
				if(!isBeat){
					//同步keys
					syncKeys(initResult);
					//开启心跳线程
					HeartBeatThread heartBeatThread=new HeartBeatThread(WeChatClass.this);
					heartBeatThread.setmNewMsgListener(mNewMsgListener);
					heartBeatThread.setmStatsMsgListener(mStatsMsgListener);
					heartBeatThread.setmExitMsgListener(mExitMsgListener);
					
					heartBeatThread.setName(skey);
					
					ThreadLostener.heartBeatThreadMap.put(skey, heartBeatThread);
					isBeat=true;
					time = Utils.getSystemTime();
					heartBeatThread.start();
				}
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String[] s = {wxsid,skey,pass_ticket,cookie};
				mInitMsgListener.onInitMsg(initResult,s);
				getFriendAndGroup(initResult);
				//System.out.println(cookie+"---------------------------InitThread\t\n"+initResult);
				
			}
	}
	
}
